<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { getGoodsDetail } from '@/api/goods'
// 导入相关的子组件
import BasicInfo from './components/BasicPage.vue'
import Description from './components/DescPage.vue'
import Reviews from './components/ReviewsPage.vue'
import Recommend from './components/RecommendPage.vue'

const route = useRoute()
const goodsId = computed(() => route.params.id)
// 默认激活的标签页是 'basic'
const activeTab = ref('basic')
const goodsDetail = ref({})

// 定义一个方法，用于获取商品详情数据
const loadGoodsDetail = async () => {
  try {
    console.log('🔄 正在加载商品详情，ID:', goodsId.value)
    const res = await getGoodsDetail(goodsId.value)
    goodsDetail.value = res
    console.log('✅ 商品详情加载完成:', goodsDetail.value)
  } catch (error) {
    console.error('❌ 获取商品详情失败:', error)
    goodsDetail.value = {}
  }
}

// 监听路由参数变化，重新加载数据
watch(() => route.params.id, (newId, oldId) => {
  if (newId && newId !== oldId) {
    console.log('🔄 检测到商品ID变化:', oldId, '→', newId)
    loadGoodsDetail()
  }
})

// 组件挂载时加载数据
// onMouted的作用是：在组件挂载时执行一次，用于初始化数据
onMounted(() => {
  loadGoodsDetail()
})
</script>

<template>
  <div class="goods-detail">
    <div class="container">
      <!-- 左侧：商品图片 -->
      <div class="goods-preview">
        <img :src="goodsDetail.image_url" :alt="goodsDetail.title">
      </div>

      <!-- 右侧：四个子页面 -->
      <div class="goods-info">
        <el-tabs v-model="activeTab" class="detail-tabs">
          <el-tab-pane label="基本信息" name="basic">
            <BasicInfo :goods="goodsDetail" />
          </el-tab-pane>

          <el-tab-pane label="详细描述" name="description">
            <Description :goods="goodsDetail" />
          </el-tab-pane>

          <el-tab-pane label="用户评价" name="reviews">
            <Reviews :goodsId="goodsId" />
          </el-tab-pane>

          <el-tab-pane label="推荐商品" name="recommend">
            <Recommend :goodsId="goodsId" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.goods-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;

  .container {
    display: flex;
    gap: 40px;

    .goods-preview {
      flex: 0 0 500px;

      img {
        width: 100%;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
      }
    }

    .goods-info {
      flex: 1;

      .detail-tabs {
        min-height: 400px;
      }
    }
  }
}
</style>
